package cn.lovingliu.chanma.service.impl;

import cn.lovingliu.chanma.form.DllCreateForm;
import cn.lovingliu.chanma.mapper.DllItemMapper;
import cn.lovingliu.chanma.mapper.DllMainMapper;
import cn.lovingliu.chanma.pojo.DllItem;
import cn.lovingliu.chanma.pojo.DllMain;
import cn.lovingliu.chanma.service.DllService;
import cn.lovingliu.chanma.util.DateUtil;
import cn.lovingliu.chanma.util.TelePhoneNumberUtil;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DllServiceimpl implements DllService {
    @Resource
    private Sid sid;
    @Resource
    private DllMainMapper dllMainMapper;
    @Resource
    private DllItemMapper dllItemMapper;

    @Override
    @Transactional
    public String createDll(DllCreateForm dllCreateForm) {
        Long nowTimestamp = DateUtil.getSecondTimestamp(new Date());
        String mainId = sid.nextShort();
        DllMain dllMain = new DllMain();

        dllMain.setId(mainId);
        dllMain.setCreatedTime(nowTimestamp);
        dllMain.setCreatedUser(dllCreateForm.getCreatedUser());

        int count = dllMainMapper.insertSelective(dllMain);
        if (count <= 0){
            return null;
        }
        int dllCount = dllCreateForm.getDllCount();
        List<String> numberList = new ArrayList<>();

        for (int num = 0;num < dllCount; num++){
            String number = createDllNumber();
            numberList.add(number);
        }

        List<DllItem> dllItemList = numberList.stream().map(number -> {
            DllItem dllItem = new DllItem();
            dllItem.setMainId(mainId);
            dllItem.setDllNumber(number);
            dllItem.setDllParent(dllCreateForm.getDllParent());
            dllItem.setDllTuijian(dllCreateForm.getDllTuijian());
            dllItem.setDllPwd(dllCreateForm.getDllPwd());
            return dllItem;
        }).collect(Collectors.toList());

        count = dllItemMapper.insertBatch(dllItemList);
        if (count > 0){
            return mainId;
        }
        return null;
    }

    private String createDllNumber(){
        String dllNumber = TelePhoneNumberUtil.getPhoneNum();
        DllItem dllItem = dllItemMapper.selectByDllNumber(dllNumber);
        if (dllItem == null){
            return dllNumber;
        }
        return createDllNumber();
    }


    @Override
    public List<DllItem> getDllWithMainId(String mainId) {
        return dllItemMapper.selectByMainId(mainId);
    }
}
